package com.ruoyi.system.interceptor;

import cn.hutool.core.text.AntPathMatcher;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.constant.AuthServiceConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description: TODO
 * @Author: jsj
 * @Date: 2022/8/23
 */
@Component
public class LoginUserInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //路径过滤
        String uri = request.getRequestURI();
        //过滤后台管理系统图片登录验证码路径
        boolean captchaImage = new AntPathMatcher().match("/captchaImage", uri);
        //过滤后台管理系统登录请求
        boolean loginUri = new AntPathMatcher().match("/login", uri);
        // boolean loginGetInfo = new AntPathMatcher().match("/getInfo", uri);
        if (captchaImage || loginUri /*|| loginGetInfo*/){
            return true;
        }

        // return HandlerInterceptor.super.preHandle(request, response, handler);
        //从redis中读取用户的登录状态
        String loginUser = stringRedisTemplate.opsForValue().get(AuthServiceConstant.LOGIN_USER);

        //从redis中读取管理员用户登录状态
        LoginUser adminLoginUser = tokenService.getLoginUser(request);
        // String loginTokens = stringRedisTemplate.opsForValue().get(AuthServiceConstant.LOGIN_TOKENS+":*");

        //普通用户登录
        if (loginUser!=null && !loginUser.equals("")) {
            System.out.println("普通用户登录");
            return true;
        }

        //管理员用户登录
        if (adminLoginUser!=null && !adminLoginUser.equals("")) {
            System.out.println("管理员用户登录");
            return true;
        }

        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
